﻿

create PROCEDURE [dbo].[proc_ConsumableMonth_Create]
(
	@ConsumableID INT,
	@ConsumableName NVARCHAR(100),
	@CompanyIdCur INT,
	@F_id INT,
	@MonthCount INT,
	@Money DECIMAL(18,2),
	@BeginMonth DATETIME,
	@C_summary NVARCHAR(300),
	@A_UserId VARCHAR(20),
	@A_UserName NVARCHAR(20)
)

AS

BEGIN TRANSACTION--开始事务
DECLARE @errorSun INT --定义错误计数器
SET @errorSun=0 --没错为0


DECLARE @MoneyMonth DECIMAL(18,2)
DECLARE @MoneyLastMonth DECIMAL(18,2)
DECLARE @Month INT
SET @Month=0
SET @MoneyMonth=@Money/@MonthCount
SET @MoneyLastMonth=@Money-@MoneyMonth*(@MonthCount-1)
BEGIN
	

	WHILE @Month<@MonthCount
	BEGIN

		IF(@Month<@MonthCount-1)
		BEGIN
			INSERT INTO [ConsumableMonth]
           ([ConsumableID]
           ,[ConsumableName]
           ,[ConsumableMoney]
           ,[ConsumableDate]
           ,[CompanyIdCur]
           ,[F_id]
           ,[C_summary]
           )
     VALUES
           (
           	@ConsumableID,
			@ConsumableName,
			@MoneyMonth,
			DATEADD(MONTH,@Month,@BeginMonth),
			@CompanyIdCur,
			@F_id,
			@C_summary
           )
		END
		ELSE 
		BEGIN
						INSERT INTO [ConsumableMonth]
           ([ConsumableID]
           ,[ConsumableName]
           ,[ConsumableMoney]
           ,[ConsumableDate]
           ,[CompanyIdCur]
           ,[F_id]
           ,[C_summary]
           )
     VALUES
           (
           	@ConsumableID,
			@ConsumableName,
			@MoneyLastMonth,
			DATEADD(MONTH,@Month,@BeginMonth),
			@CompanyIdCur,
			@F_id,
			@C_summary
           )
		END

  if @@ROWCOUNT<1
	begin
		set @errorSun=@errorSun+1		
		goto e;
	END


		SET @Month=@Month+1
		
		
	END


UPDATE Finance_Outlay
SET
	
	A_txflag = 1,
	A_txqsy = convert(varchar(10),@BeginMonth,120),
	A_txys = @MonthCount,
	A_txbz = '摊销类别：'+@ConsumableName+'(摊销月数：'+convert(varchar, @MonthCount)+')',
	A_UserName = @A_UserName,
	A_UserId = @A_UserId,
	A_Date = GETDATE()
WHERE id=@F_id AND A_txflag=0

  if @@ROWCOUNT<1
	begin
		set @errorSun=@errorSun+1		
		goto e;
	END
	
	
e:
    PRINT @errorSun
	if @errorSun>0
	begin
		rollback TRANSACTION
	
	end
	else
	begin
		commit TRANSACTION
	END
END


